//
//  SettingViewController.swift
//  Reader
//
//  Created by wang shuguan on 5/11/21.
//  Copyright © 2021 codeguesser. All rights reserved.
//

import UIKit

class SettingViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    var models = ["设置背景图片","设置文字","黑夜模式","白天模式"]{
        didSet{
            tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "设置"
        self.navigationItem.largeTitleDisplayMode = .automatic
        self.navigationItem.title = "设置"
        self.navigationController?.navigationBar.prefersLargeTitles = true
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(cleanData))
        changeTopConstraint()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = models[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if models[indexPath.row] == "设置背景图片"{
            changeImage { (url) in
                Preference.background = url.lastPathComponent
                UIAlertController.alertMessage("设置成功")
            }
        }else if models[indexPath.row] == "设置文字"{
            UIAlertController.alertTextField(title: "", textFieldPlaceholder: [("设置颜色", false)], btnTitles: ["确定","取消"]) { (vc, index) in
                if index == 0,let tf = vc.textFields?.first{
                    Preference.textColor = tf.text
                    UIAlertController.alertMessage("设置成功")
                }
            }
        }else if models[indexPath.row] == "黑夜模式"{
            Preference.textColor = "ffffff"
            Preference.background = "2.heic"
            UIAlertController.alertMessage("设置成功")
        }else if models[indexPath.row] == "白天模式"{
            Preference.textColor = "333333"
            Preference.background = "1.heic"
            UIAlertController.alertMessage("设置成功")
        }
    }
    @objc func cleanData() {
        Preference.background = nil
        Preference.textColor = nil
        UIAlertController.alertMessage("清除成功")
    }
    func changeImage(block:@escaping((URL)->Void)) {
        func uploadFile(url:URL) {
            var copyedURL:URL?
            if let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).first{
                let newPath = dir + "/" + url.lastPathComponent
                do {
                    
                    func newName(oldPath:String,index:Int)->String{
                        var p = oldPath
                        if index > 0 {
                            let u = URL(fileURLWithPath: oldPath)
                            p = u.path.replacingOccurrences(of: "."+u.pathExtension, with: "_\(index)."+u.pathExtension)
                        }
                        if FileManager.default.isReadableFile(atPath: p) {
                            return newName(oldPath: oldPath, index: index + 1)
                        }else{
                            return p
                        }
                    }
                    try FileManager.default.copyItem(atPath: url.path, toPath: newName(oldPath: newPath, index: 0))
                    copyedURL = URL(fileURLWithPath: newPath, isDirectory: false)
                    
                    if let _copyedURL = copyedURL{
                        var dic:[FileAttributeKey : Any] = [:]
                        do{
                            dic = try FileManager.default.attributesOfItem(atPath: _copyedURL.path)
                        }catch{
                            ZWTPrint(error)
                        }
                        guard (dic[FileAttributeKey.size] as? Int64 ?? 0) / 1024 / 1024 < 200 else {
                            UIAlertController.alertMessage("上传文件不得超过200MB")
                            return
                        }
                        block(_copyedURL)
                    }
                } catch  {
                    UIAlertController.alertMessage(error.localizedDescription)
                    return
                }
            }
        }
        UIAlertController.alertMessage("上传图像", title: " ", btnTitles: ["本地照片","拍照","浏览文件","取消"],action: {(index) in
            if index == 0{
                updatePhotoToServer(by: .photoLibrary){ url in
                    uploadFile(url: url)
                }
                ZWTPrint("本地照片")
            }else if index == 1{
                updatePhotoToServer(by: .camera){ url in
                    uploadFile(url: url)
                }
                ZWTPrint("拍照")
            }else if index == 2{
                addByFile(){ url in
                    uploadFile(url: url)
                }
            }else{
                ZWTPrint("取消")
            }
        })
        
        func updatePhotoToServer(by way:UIImagePickerController.SourceType,block:@escaping((URL)->Void)) -> Void {
            if UIImagePickerController.isSourceTypeAvailable(way) {
                let imagevc = UIImagePickerController()
                imagevc.sourceType = way;
                imagevc.addSelectedBlock({(img,_) in
                    if let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).first{
                        let url = URL(fileURLWithPath: dir + "/\(Date().timeIntervalSince1970).png")
                        do {
                            try img.scaleToFitSize().pngData()?.write(to: url)
                            block(url)
                        } catch {
                            
                        }
                    }
                })
                self.present(imagevc, animated: true, completion: nil)
            }
        }
        func addByFile(block:@escaping((URL)->Void)){
            let vc = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .import)
            vc.addSelectedBlock { (url) in
                if let _url = url{
                    block(_url)
                }
            }
            self.present(vc, animated: true, completion: nil)
        }
    }
}
